"use strict";
const semver = require("semver");
const log = require("@ysj-cli-dev/log");
const colors = require("colors/safe");
const userHome = require("user-home");
const pathExists = require("path-exists").sync;
const path = require("path");

const pkg = require("../package.json");
const constant = require("./const");

let args;

async function core() {
  // TODO
  try {
    checkPkgVersion();
    checkNodeVersion();
    checkRoot();
    checkHome();
    checkInputArgs();
    log.verbose("debug", "rtest");
    checkenv()
    await checkGlobalUpdate()
  } catch (error) {
    log.error(error.message);
  }
}

function checkNodeVersion() {
  // 拿到版本号
  // 对比最低版本号
  const currentVersion = process.version;
  const lowestVersion = constant.LOWEST_NODE_VERSION;
  if (!semver.gte(currentVersion, lowestVersion)) {
    throw new Error(colors.red(`ysj-cli 需要安装v${lowestVersion}以上的版本`));
  }
}

function checkPkgVersion() {
  log.error("cli", pkg.version);
}

function checkRoot() {
  const rootCheck = require("root-check");
  rootCheck();
  // console.log('qw4 after', process.getuid())
}

function checkHome() {
  if (!userHome || !pathExists(userHome)) {
    throw new Error(colors.red("当前登录用户主目录不存在"));
  }
}

function checkInputArgs() {
  const minimist = require("minimist");
  args = minimist(process.argv.slice(2));
  checkArgs();
}

function checkArgs() {
  if (args.debug) {
    process.env.LOG_LEVEL = "verbose";
  } else {
    process.env.LOG_LEVEL = "info";
  }
  log.level = process.env.LOG_LEVEL;
}

function checkenv() {
  const dotenv = require("dotenv");
  const dotenvPath = path.resolve(userHome, ".env");
  console.log('dotenvPath', dotenvPath)
  if (pathExists(dotenvPath)) {
    dotenv.config({
      path: dotenvPath,
    });
  }
  createDefaultConfig()
  log.verbose("环境变量", process.env.CLI_HOME_PATH);
}

function createDefaultConfig() {
    const cliConfig = {
        home: userHome,
    }
    if(process.env.CLI_HOME) {
        cliConfig['cliHome'] = path.join(userHome, process.env.CLI_HOME);
    } else {
        cliConfig['cliHome'] = path.join(userHome, constant.DEFAULT_CLI_HOME)
    }

    process.env.CLI_HOME_PATH = cliConfig.cliHome
}

async function checkGlobalUpdate() {
    // 1.获取当前版本号和模块名
    const currentVersion = pkg.version
    const npmName = pkg.name
    // 2.调用npm API,获取所有的版本号
    // 3.提取所有版本号，比对哪些版本号是大于当前版本号
    const { getNpmSemverVersion } = require("@ysj-cli-dev/get-npm-info")
    const lastVersion = await getNpmSemverVersion(currentVersion, npmName);
    if(lastVersion && semver.gt(lastVersion, currentVersion)) {
        log.warn(colors.yellow(`请手动更新${npmName},当前版本:${currentVersion},最新版本:${lastVersion}
                更新命令为： npm install -g ${npmName}
        `))
    }

   
    
}

module.exports = core;
